<?php

namespace Application\Model;

use Zend\Db\Adapter\Adapter;
use Zend\Db\Sql\Sql;
use Zend\Db\ResultSet\ResultSet;
use Zend\Db\TableGateway\TableGateway;
use Zend\Db\Sql\Select;

class ContactTable
{
    protected $table ='Contact';
    protected $tableName ='Contact';
    
    protected $tableGateway;

    public function __construct(TableGateway $tableGateway)
    {
    	$this->tableGateway = $tableGateway;
    }
    
    public function fetchAll()
    {
        $resultSet = $this->tableGateway->select(function(Select $select){
            $select->order('idContact ASC');
        });
        
        return $resultSet;
    }

    public function fetchAllArray()
    {
        $resultSet = $this->fetchAll();
        $entities = array();
        
        foreach ($resultSet as $row) {
        	$obj = new Contact();
        	$obj->exchangeArray( (array) $row);
        	$entities[] = $obj;
        }
        
        return $entities;
    }

    public function toArray ($resultSet)
    {
        $entities = array();
        
        foreach ($resultSet as $row) {
            $obj = new Contact();
            $obj->exchangeArray( (array) $row);
            $entities[] = $obj;
        }
        
        return $entities;
    }

    public function isDemanceContactDejaEnBase( Contact $Contact )
    {
        $mailContact = $Contact->mailContact;

        if( $mailContact == null || $mailContact == "" ) {
            return false;
        }

        $creation = date('Y-m-d H:i:s', strtotime("-1 hours"));

        $resultSet = $this->tableGateway->select(function(Select $select) use($mailContact, $creation) {
            $select->where->greaterThanOrEqualTo('dateContact', $creation);
            $select->where->equalTo('mailContact', $mailContact);
        });

        return count($resultSet) > 0;
    }

    public function saveDemandeFormulaireDeContact(Contact $Contact)
    {
        $data = (array) $Contact;
        
        $id = (int)$Contact->idContact;
        
        if ($id == 0) {
            $this->tableGateway->insert($data);
            
            $id = $this->tableGateway->lastInsertValue;
            
        }
        
        return $id;
    }
}